module(..., package.seeall)

require ("markdown")


SputnikMarkupMarkdown = {

   ----------------------------------------------------------------------------
   -- Creates a new "markup" object
   -- 
   -- @params none
   ----------------------------------------------------------------------------


   new = function (self)

      local obj = {}

      setmetatable(obj, self)
      self.__index = self
      return obj         
   end,


    --- Turn a string of text into a wikilink ----------------------------------

   wikify = function (self, wikilink, templates, helpers)

      -- [[Page_Name.edit#A1|Edit the Page]]

      local title, page_name, exists, link

      wikilink, title   = helpers:split(wikilink, "|")
      wikilink, anchor  = helpers:split(wikilink, "#")
      page_name, action = helpers:split(wikilink, "%.")

      title = title or page_name
      page_name = helpers:dirify(page_name)

      exists = true --helpers.storage:page_exists(page_name)
      if exists then
	  	link = helpers:make_link(page_name)
	  	if anchor then
	    	link = link.."#"..anchor
	 	end
      else 
	 	link = helpers:make_link(page_name)
      end
      return helpers:format_wikilink(title, link, exists, templates)
   end,



   ----------------------------------------------------------------------------
   -- Returns a text wikified.
   --
   -- @param       text - the original text
   -- @param       templates - some templates
   -- @param       base_url - the base url when resolving links (not necessary, just for compatibility with the POD module)
   -- @param       helpers - a Sputnik object
   -- @return      the text wikified
   ----------------------------------------------------------------------------

   wikify_text = function (self, text, templates, base_url, helpers)
   	  require ("markdown")
	  local content = string.gsub(text, "%[%[([^%]]*)%]%]", 
				  function(text) 
				     return self:wikify(text, templates, helpers)
				  end)
      return markdown (content)
   end

}


open = function() return SputnikMarkupMarkdown:new(base_url) end

